{% extends "core.html" %}
{% block main_pane %}
<div>
    <div id="main-pane"
        style="width: 100%; height: {{frame_height}}px; background-color: #dff0d8; padding: 30px; overflow:scroll;">
        <span>
            <h3>Task Description</h3>
            <div>To first learn about the labeling task, please evaluate the "THEM"
                speaker in the conversation below, choosing the correct checkboxes.</div>
            <br><br>
            <div id="onboarding-pane" style="width: 850px;margin: 0px auto;border: 1px solid
        #dcdcdc;padding:5px">
                Loading sample conversation...
                <div style='clear:both'></div>
            </div>
        </span>
        <hr style="border-top: 1px solid #555" />
        <div>
            <div id="response-type-text-input" class="response-type-module"
                style="padding-left: 35px; padding-top: 30px; padding-bottom: 30px; padding-right: 35px; float: left;">
                <div style="height: 50px; width: 100%; display: block; float: left;">
                    <button class="btn btn-primary" style="width: 230px; height: 100%;
            font-size: 16px; float: left; margin-left: 10px; padding: 0px;" id="id_submit_onboarding_answers">Submit
                        Answers</button>
                    <button class="btn btn-primary" style="width: 230px; height: 100%;
            font-size: 16px; float: left; margin-left: 10px; padding: 0px; display:none;" id="id_send_msg_button"
                        disabled>Continue to HIT</button>
                </div>
            </div>
            <div id="response-type-waiting" class="response-type-module"
                style="height: 50px; width: 100%; display: block; float: left; ">
                <span id="waiting"
                    style="font-size: 16pt; padding-top: 30px; padding-left: 30px; margin-right: 15px">Now
                    waiting for another worker to join the chat...</span>
            </div>
        </div>
    </div>
    <div id="bottom-pane" style="width: 100%; background-color: #eee;">
        <div id="response-type-idle" class="response-type-module" style="display:none">
        </div>
        <div id="response-type-done" class="response-type-module"
            style="padding-left: 35px; padding-top: 30px; padding-bottom: 30px; padding-right: 35px; float: left; display:none">
            <span id="disconnect" style="font-size: 14pt;margin-right: 15px"></span>
            <button id="done-button" type="button" class="btn btn-primary btn-lg">
                <span class="glyphicon glyphicon-ok-circle" aria-hidden="true"></span> Done with this HIT
            </button>
        </div>
        <div id="response-type-inactive" class="response-type-module"
            style="padding-left: 35px; padding-top: 30px; padding-bottom: 30px; padding-right: 35px; float: left">
            <span id="inactive" style="font-size: 16px"></span>
        </div>
    </div>
</div>
{% endblock %}

{% block additional_scripts %}
<script type="text/javascript">
    var ANNOTATIONS_CONFIG = null;
    var count_incorrect_attempts = 0;
    var ONBOARD_FAIL = '[ONBOARD_FAIL]';
    var ONBOARD_TRY_AGAIN = '[ONBOARD_TRY_AGAIN]';
    var ONBOARD_SUBMIT = '[ONBOARD_SUBMIT]';

    var displayCheckboxDescription = function (mIdx, evt) {
        if ($(evt.target).is(":checked")) {
            var checkboxId = $(evt.target).attr('id');
            var description = $(evt.target).attr('ta-description');
            var prettyName = $(evt.target).attr('ta-pretty-name');
            $("#explanation_" + mIdx).html('You labeled this as <b>' + prettyName + '</b>, meaning that: ' + description);
        } else {
            $("#explanation_" + mIdx).html('');
        }
    };

    var setupOnboardingTask = function (msg) {
        $("#onboarding-pane").html(msg['onboarding_html']);
        ANNOTATIONS_CONFIG = msg['annotations_config'];
        console.log('Found ' + $('input[name^="checkbox_group_"]').length + ' annotations with config: ' + JSON.stringify(ANNOTATIONS_CONFIG));
        var allOnboardingCheckboxGroups = [$('input[name="checkbox_group_1"]'), $('input[name="checkbox_group_3"]'), $('input[name="checkbox_group_5"]'), $('input[name="checkbox_group_7"]'), $('input[name="checkbox_group_9"]')];
        for (var i = 0; i < allOnboardingCheckboxGroups.length; i++) {
            var cg = allOnboardingCheckboxGroups[i];
            var cgName = cg.attr('name');
            var messageIdx = parseInt(cgName[cgName.length - 1]);
            cg.click(displayCheckboxDescription.bind(this, messageIdx));
        }
    };

    var renderOnboardingFail = function () {
        // Update the UI
        $("button#id_submit_onboarding_answers").css("display", "none");

        alert('Sorry, you\'ve exceeded the maximum amount of tries to label the sample conversation correctly, and thus we don\'t believe you can complete the task correctly. Please return the HIT.')

        // For some reason it seems like this HTML message does not show up for 
        // some turkers? (Got email saying the button disappeared - so they 
        // failed - but they could still see their answers, so were confused.)
        $("#main-pane").html('<div style="text-align:center;font-size:2em;margin-top:10%;padding:50px;">Sorry, you\'ve exceeded the maximum amount of tries to label the sample conversation correctly, and thus we don\'t believe you can complete the task correctly. Please return the HIT.</div>')

        // Redraw UI
        $(window).resize();

        // Need to wait to close the socket otherwise the backend won't 
        // received the failed message to soft ban the worker
        // window.setTimeout(close_socket, 10000);
    }

    var old_msg_function = handle_new_message
    handle_new_message = function (new_message_id, message) {
        console.log('Onboarding received message in handle_new_message: ' + JSON.stringify(message));
        if (message.text === undefined) {
            console.log('Got message with text undefined. Going to display the waiting message.');
            $("div#response-type-waiting").css("display", "");
            return
        }
        old_msg_function.apply(old_msg_function, [new_message_id, message])
        console.log(message);
        if ('onboarding_html' in message) {
            // Initial message, need to render the onboarding task
            setupOnboardingTask(message);
        } else if (message.text == ONBOARD_TRY_AGAIN) {
            alert('You did not label the sample conversation well enough. Please try one more time!');
            $('button#id_submit_onboarding_answers').removeClass("disabled");
            $('button#id_submit_onboarding_answers').prop("disabled", false);
        } else if (message.text == ONBOARD_FAIL) {
            // Tell user to return the HIT
            renderOnboardingFail();
        } else {
            console.log('Received unknown message type: ' + JSON.stringify(message));
        }

    }
    // Using evt.preventDefault() did not seem to prevent the send msg button from getting clicked and it advanced the page to the HIT
    $('#id_submit_onboarding_answers').click(function () {
        console.log('Submitting onboarding answers...');
        $('button#id_submit_onboarding_answers').addClass("disabled");
        $('button#id_submit_onboarding_answers').prop("disabled", true);
        var annotationBuckets = ANNOTATIONS_CONFIG.map(function(a) {
            return a['value'];
        })

        var allOnboardingCheckboxGroups = [$('input[name="checkbox_group_1"]'), $('input[name="checkbox_group_3"]'), $('input[name="checkbox_group_5"]'), $('input[name="checkbox_group_7"]'), $('input[name="checkbox_group_9"]')];
        var userAnswers = {};
        // Get the answers that the user clicked from the checkboxes
        for (var i = 0; i < allOnboardingCheckboxGroups.length; i++) {
            var cg = allOnboardingCheckboxGroups[i];
            var cgName = cg.attr('name');
            var messageIdx = parseInt(cgName[cgName.length - 1]);
            var answersForIdx = []
            annotationBuckets.map(function (k) {
                var isChecked = $('#checkbox_' + k + '_' + messageIdx + ':checked').val();
                if (isChecked == 'on') {
                    answersForIdx.push(k)
                }
            });
            // dictionary so keys will be 1,3,5,7,9
            userAnswers[messageIdx] = answersForIdx;
        }

        newMessageId = uuidv4();
        send_packet(
            TYPE_MESSAGE,
            {
                text: '[ONBOARD_SUBMIT]',
                id: cur_agent_id,
                message_id: newMessageId,
                onboard_submission: userAnswers,
                episode_done: false,
            },
            true,
            true,
            null
        );
    });

    function window_resize() {
    }
    $(window).resize(window_resize);
    function scroll_conversation_to_bottom() { }
    function scroll_conversation_to_bottom() {
        $('div#main-pane').animate({
            scrollTop: 0
        }, 500);
    }
</script>
{% endblock %}